class TransportesController < ApplicationController
    before_filter :load_items, :only => [:new, :create, :edit, :update, :editarstatus, :updatestatus]
    
    caches_page :new
    cache_sweeper :state_sweeper

    def index
    end

    def new
        @transporte = Transporte.new
        @transporte.created_at = Deposito.new.current_time.to_s_br[0..9]
    end

    def create
        @transporte = Transporte.new()
        @transporte.status_id = 15 #Inicia-se como GERADO
        @transporte.m = params[:transporte][:m].to_i  if params[:transporte][:m].to_i != ""
        @transporte.transportadora_id = params[:transporte][:transportadora] if params[:transporte][:transportadora] != ""
        @transporte.ndt = params[:transporte][:ndt] if params[:transporte][:ndt] != ""
        @transporte.destino_id = params[:transporte][:destino] if params[:transporte][:destino] != ""
        @transporte.itinerario = params[:transporte][:itinerario] if params[:transporte][:itinerario] != ""
        @transporte.pares = params[:transporte][:pares] if params[:transporte][:pares] != ""
        @transporte.peso = params[:transporte][:peso] if params[:transporte][:peso] != ""
        @transporte.cxs = params[:transporte][:cxs] if params[:transporte][:cxs] != ""
        @transporte.tipo_id = params[:transporte][:tipo] if params[:transporte][:tipo] != ""
        @transporte.obs_trans = params[:transporte][:obs_trans] if params[:transporte][:obs_trans] != ""
        if params[:transporte][:created_at] != ""
            data = params[:transporte][:created_at].to_s
            dia = data[0..1]
            mes = data[3..4]
            ano = data[6..9]
            @transporte.created_at = Time.zone.parse("#{ano}-#{mes}-#{dia} #{Deposito.new.current_time.hour}:#{Deposito.new.current_time.min}:#{Deposito.new.current_time.sec}")
        end
        @transporte.etiqueta = params[:transporte][:etiqueta] if params[:transporte][:etiqueta] != ""
        @transporte.carro = params[:transporte][:carro] if params[:transporte][:carro] != ""
        @transporte.user = current_user

        respond_to do |format|
            if @transporte.save
                @depositos = Deposito.find(:all)
                @depositos.each do |d|
                    x = params["deposito_#{d.id}".to_sym][:checkbox]
                    if ( x != "0")
                        cxs =  params["deposito_#{d.id}".to_sym][:quantidade_cxs]
                        box = params["deposito_#{d.id}".to_sym][:box]
                        pares = params["deposito_#{d.id}".to_sym][:quantidade]
                        unless @transporte.armazenamentos.create(:deposito => d, :cxs => cxs, :box => box, :pares => pares)
                            break
                            Transporte.delete(@transporte)
                            flash[:error] = 'Ocorreu algum problema ao criar o transporte e amazenamentos!'
                            format.html { redirect_to new_transporte_path }
                        end
                    end
                end
                flash[:notice] = 'Transporte criado com sucesso!'
                format.html { redirect_to new_transporte_path }
            else
                format.html { render :action => "new" }
                format.xml  { render :xml => @transporte.errors.to_xml }
            end
        end
    end

    def edit
        @transporte = Transporte.find(params[:id])
        unless @transporte.ended_at.nil?
            ended_at = @transporte.ended_at.to_s.gsub('-', '/')
            ano, mes, dia, hora, minuto = ended_at[0..3], ended_at[5..6], ended_at[8..9], ended_at[11..12], ended_at[14..15]

            @ended_at =  @transporte.ended_at.to_s_br[0..9]
            @hora,@minuto = @transporte.ended_at.to_s_br[11..12].to_i, @transporte.ended_at.to_s_br[14..15].to_i
        else
            @ended_at = Deposito.new.current_time.to_s_br[0..9]
            @hora,@minuto = Deposito.new.current_time.hour, Deposito.new.current_time.min
        end
    end

    def update
        @transporte = Transporte.find(params[:id])

        @depositos = Deposito.find(:all)
        armazenamentos = []
        @depositos.each do |d|
            x = params["deposito_#{d.id}".to_sym][:checkbox]
            if ( x != "0")
                cxs =  params["deposito_#{d.id}".to_sym][:quantidade_cxs]
                box = params["deposito_#{d.id}".to_sym][:box]
                pares = params["deposito_#{d.id}".to_sym][:quantidade]

                arm = Armazenamento.new
                arm.deposito = d
                arm.cxs = cxs
                arm.box = box
                arm.pares = pares
                armazenamentos << arm
            end
        end

        respond_to do |format|
            if armazenamentos.empty?
                flash[:error] = 'Escolha pelo menos depóstio!'
                format.html { redirect_to new_transporte_path }
            else
                if params[:transporte][:created_at] != ""
                    data = params[:transporte][:created_at].to_s
                    dia = data[0..1]
                    mes = data[3..4]
                    ano = data[6..9]
                    created_at = Time.zone.parse("#{ano}-#{mes}-#{dia} #{Deposito.new.current_time.hour}:#{Deposito.new.current_time.min}:#{Deposito.new.current_time.sec}")
                else
                    created_at = nil
                end

                @transporte.m = params[:transporte][:m]
                @transporte.transportadora_id = params[:transporte][:transportadora]
                @transporte.ndt = params[:transporte][:ndt]
                @transporte.destino_id = params[:transporte][:destino]
                @transporte.itinerario = params[:transporte][:itinerario]
                @transporte.pares = params[:transporte][:pares]
                @transporte.peso = params[:transporte][:peso]
                @transporte.cxs = params[:transporte][:cxs]
                @transporte.tipo_id = params[:transporte][:tipo]
                @transporte.obs_trans = params[:transporte][:obs_trans]
                @transporte.created_at = created_at
                @transporte.status_id = params[:transporte][:status]
                @transporte.etiqueta = params[:transporte][:etiqueta]
                @transporte.carro = params[:transporte][:carro]
                @transporte.armazenamentos = armazenamentos
                @transporte.user = current_user
                if Transporte.new.isfaturamento?(params[:transporte][:status].to_i)
                    ended_at_dia = params[:transporte][:ended_at][0..1]
                    ended_at_mes = params[:transporte][:ended_at][3..4]
                    ended_at_ano = params[:transporte][:ended_at][6..9]
                    ended_at_hora = params[:date][:hour]
                    ended_at_minuto = params[:date][:minute]
					#date = DateTime.parse("#{ended_at_ano}-#{ended_at_mes}-#{ended_at_dia} #{ended_at_hora}:#{ended_at_minuto}:00")
					@transporte.ended_at = Time.zone.parse("#{ended_at_ano}-#{ended_at_mes}-#{ended_at_dia} #{ended_at_hora}:#{ended_at_minuto}:00")
                else
                    @transporte.ended_at = nil
                end

                if @transporte.save
                    format.html {redirect_to(session[:voltar_para])}
                    flash[:notice] = 'Transporte atualizado com sucesso!'
                else
                    format.html { render :action => "edit" }
                end
            end
        end
    end

    def editarstatus
        @transporte = Transporte.find(params[:id])
        unless @transporte.ended_at.nil?
            ended_at = @transporte.ended_at.to_s.gsub('-', '/')
            ano, mes, dia, hora, minuto = ended_at[0..3], ended_at[5..6], ended_at[8..9], ended_at[11..12], ended_at[14..15]

            @ended_at =  @transporte.ended_at.to_s_br[0..9]
            @hora,@minuto = @transporte.ended_at.to_s_br[11..12].to_i, @transporte.ended_at.to_s_br[14..15].to_i
        else
            @ended_at = Deposito.new.current_time.to_s_br[0..9]
            @hora,@minuto = Deposito.new.current_time.hour, Deposito.new.current_time.min
        end
    end

    def updatestatus
        respond_to do |format|

            @transporte = Transporte.find(params[:id])

            @transporte.armazenamentos.each do |armazenamento|
                box = params["deposito_#{armazenamento.deposito.id}".to_sym][:box]
                armazenamento.update_attribute(:box, box)
            end

            @transporte.update_attributes(:obs_trans => params[:transporte][:obs_trans],
                    :status_id => params[:transporte][:status_id],
                    :etiqueta  => params[:transporte][:etiqueta ],
                    :carro  => params[:transporte][:carro])
            if Transporte.new.isfaturamento?(params[:transporte][:status_id].to_i)
                ended_at_dia = params[:transporte][:ended_at][0..1]
                ended_at_mes = params[:transporte][:ended_at][3..4]
                ended_at_ano = params[:transporte][:ended_at][6..9]
                ended_at_hora = params[:date][:hour]
                ended_at_minuto = params[:date][:minute]
				#date = DateTime.parse("#{ended_at_ano}-#{ended_at_mes}-#{ended_at_dia} #{ended_at_hora}:#{ended_at_minuto}:00")
                @transporte.ended_at = Time.zone.parse("#{ended_at_ano}-#{ended_at_mes}-#{ended_at_dia} #{ended_at_hora}:#{ended_at_minuto}:00")
            else
                @transporte.ended_at = nil
            end

            if @transporte.save
				#format.html {redirect_to(session[:voltar_para])}
				format.html {redirect_to(session[:voltar_para])}
                flash[:notice] = "Transporte atualizado com sucesso!"
            else
                format.html { render :action => "editarstatus" }
            end
        end

    end
	
	def existendt
		if Transporte.find_by_ndt(params[:ndt]).nil?
			ndt = {:ndt => 0.to_s}			
		else
			ndt = {:ndt => 1.to_s}
		end
		
		render :xml => ndt.to_xml, :layout => false
	end

	def cancelados	
	prawnto :prawn => {:page_layout => :landscape, :page_size => "A4"}	
	
		@transportes = Transporte.find_all_by_status_id($CANC, :include => [ :status, :depositos ], :order => 'depositos.nome asc, statuses.sigla asc, ndt asc')
  
		respond_to do |format|
			format.html { session[:voltar_para] = request.request_uri }
			format.js  {render :text=> to_json_text(@transportes)}
			format.xml {render :xml => @transportes.to_xml}
			format.pdf {}
		end	
	end
	
	def liberados
	prawnto :prawn => {:page_layout => :landscape, :page_size => "A4"}	
	
		@transportes = Transporte.find_all_by_status_id($LIB, :include => [ :status, :depositos ], :order => 'depositos.nome asc, statuses.sigla asc, ndt asc')
  
		respond_to do |format|
			format.html { session[:voltar_para] = request.request_uri }
			format.js  {render :text=> to_json_text(@transportes), :layout => false}
			format.pdf {}
			format.xml {render :xml => @transportes.to_xml, :layout => false}
			format.xls {render :text => @transportes.to_xls, :layout => false}
			format.csv {render :text => @transportes.to_csv, :layout => false}
		end		
	end	
	
	def gerais
	prawnto :prawn => {:page_layout => :landscape, :page_size => "A4"}	
	
	transportes = Transporte.find(:all, :conditions =>['status_id != ? and status_id != ?',"#{$LIB}","#{$CANC}"],
					:include => [ :status, :depositos ], :order => 'depositos.nome asc, statuses.sigla asc, ndt asc')
					
    @transportes = transportes				
	
		respond_to do |format|
			format.html { session[:voltar_para] = request.request_uri }
			format.js   { render :text => to_json_text(transportes) }
			format.xml  { render :xml => transportes.to_xml }
			format.xls {render :text => @transportes.to_xls, :layout => false}			
			format.pdf {}			
		end			
	end
	
	def wm
		prawnto :prawn => {:page_layout => :landscape, :page_size => "A4"}
		
		@transportes = Transporte.find(:all, :conditions =>['status_id != ? and status_id != ?',"#{$LIB}","#{$CANC}"],
					:include => [ :status, :depositos ], :order => 'depositos.nome asc, statuses.sigla asc, ndt asc')
				
		respond_to do |format|
			format.html { session[:voltar_para] = request.request_uri }
			format.js  {render :text=> to_json_text(@transportes)}
			format.xml {render :xml => @transportes.to_xml}
			format.pdf {}
		end			
	end
	
	def faturados
		prawnto :prawn => {:page_layout => :landscape, :page_size => "A4"}
		
		 conditions = [$CDO_CNF, $GDO_CNF, $SEP_CNF, $CNDO_CNF, $CONF_CNF]
		
		@transportes = Transporte.find(:all, :conditions =>['status_id IN (?) ', conditions],
					:include => [ :status, :depositos ], :order => 'depositos.nome asc, statuses.sigla asc, ndt asc')
				
		respond_to do |format|
			format.html { session[:voltar_para] = request.request_uri }
			format.js  {render :text=> to_json_text(@transportes)}
			format.xml {render :xml => @transportes.to_xml}
			format.pdf {}
		end			
	end	
	
	def celcli
		prawnto :prawn => {:page_layout => :landscape, :page_size => "A4"}
		
		@transportes = Transporte.find(:all, :conditions =>['status_id != ? and status_id != ?',"#{$LIB}","#{$CANC}"],
					:include => [ :status, :depositos ], :order => 'depositos.nome asc, statuses.sigla asc, ndt asc')
				
		respond_to do |format|
			format.html { session[:voltar_para] = request.request_uri }
			format.js  {render :text=> to_json_text(@transportes)}
			format.xml {render :xml => @transportes.to_xml}
			format.pdf {}
		end			
	end

	def faturadosdia
		prawnto :prawn => {:page_layout => :landscape, :page_size => "A4"}
		
		@depositos = Deposito.all
		status = [$FAT, $LIB, $CDO_CNF, $GDO_CNF, $SEP_CNF, $CNDO_CNF, $CONF_CNF]		
		@deposito_quantidade = @depositos.size.to_i
		inicio = Deposito.new.current_time.beginning_of_month
		fim =  inicio.end_of_day
		dias_mes = Deposito.new.current_time.end_of_month.day.to_i
		u = fim.day.to_i
		
		return_data = {}
		depositos = []
		
		(1..dias_mes).each do |t|
		
			deposito = []
			total = 0
			@depositos.each do |d|
				condicoes = ["armazenamentos.deposito_id = ? and  transportes.status_id IN (?) and transportes.ended_at > ? and transportes.ended_at < ?", d.id, status, inicio, fim]					
				valor = Transporte.sum("armazenamentos.pares", :include => :armazenamentos, :conditions => condicoes)	
				deposito << d.nome.to_s.downcase_br.to_sym				
				deposito << valor.para_dinheiro.to_s_m
				total += valor
			end
			deposito << "total".to_sym
			deposito << total.para_dinheiro.to_s_m
			
			deposito << "data".to_sym
			deposito << inicio.strftime("%d/%m/%Y")
			
			depositos << Hash[*deposito]
			
			inicio = inicio + 1.day
			fim = fim + 1.day
		end
		
		return_data[:depositos] = depositos
		return_data[:total] = return_data[:depositos].size
		
		@return_data = return_data
		
		respond_to do |format|
			format.html {}
			format.js  {render :text => return_data.to_json}
			format.xml {}
			format.pdf {}
		end			
	end		
	
	def faturadosmes	
		prawnto :prawn => {:page_layout => :landscape, :page_size => "A4"}
		
		@depositos = Deposito.all
		status = [$FAT, $LIB, $CDO_CNF, $GDO_CNF, $SEP_CNF, $CNDO_CNF, $CONF_CNF]		
		@deposito_quantidade = @depositos.size.to_i
	
		return_data = {}
		depositos = []
		
		(1..12).each do |t|
				
			mes = Time.zone.local(Deposito.new.current_time.year,t.to_i)
			inicio, fim = mes.beginning_of_month, mes.end_of_month		
		
			deposito = []
			total = 0
			@depositos.each do |d|
				condicoes = ["armazenamentos.deposito_id = ? and  transportes.status_id IN (?) and transportes.ended_at > ? and transportes.ended_at < ?", d.id, status, inicio, fim]					
				valor = Transporte.sum("armazenamentos.pares", :include => :armazenamentos, :conditions => condicoes)	
				valor += d.faturamento_anterior(d.id, mes) 
				deposito << d.nome.to_s.downcase_br.to_sym				
				deposito << valor.para_dinheiro.to_s_m
				total += valor
			end
			deposito << "total".to_sym
			deposito << total.para_dinheiro.to_s_m
			
			deposito << "data".to_sym
			deposito << inicio.strftime("%m/%Y")
			
			depositos << Hash[*deposito]
			
			inicio = inicio + 1.month
			fim = fim + 1.month			
		end
		
		return_data[:depositos] = depositos
		return_data[:total] = return_data[:depositos].size
		
		nome_depositos = Deposito.all(:order => "nome ASC").map {|d| d.nome.to_s.downcase.to_sym}		
				
		a = []
		return_data[:depositos].each do |linha|
			nome_depositos.each do |nome|
				linha[nome]
			end
		end
		
		@return_data = return_data
	
		respond_to do |format|
			format.html {}
			format.js  {render :text => return_data.to_json}
			format.xml {}
			format.pdf {}
		end			
	end		
	
	def to_json_text(transportes)
		
        return_data = Hash.new()      
        return_data[:total] = transportes.size
        return_data[:transportes] = transportes.collect{|u| 
											ended_at = u.ended_at.nil? ? nil : u.ended_at.strftime('%d/%m/%Y %H:%M:%S').to_s
											created_at = u.created_at.nil? ? nil : u.created_at.strftime('%d/%m/%Y %H:%M:%S').to_s
											updated_at = u.updated_at.nil? ? nil : u.updated_at.strftime('%d/%m/%Y %H:%M:%S').to_s
											released_at = u.released_at.nil? ? nil : u.released_at.strftime('%d/%m/%Y %H:%M:%S').to_s
											entrou_em_box = u.entrou_em_box.nil? ? nil : u.entrou_em_box.strftime('%d/%m/%Y %H:%M:%S').to_s
											em_box = u.entrou_em_box.nil? ? nil : u.tempo_em_box
											{
											:id =>u.id, 
                                            :ndt => u.ndt,
                                            :pares =>u.pares, 
                                            :cxs =>u.cxs, 
                                            :m =>u.m, 
											:peso => u.peso,
                                            :destino_id =>u.destino.sigla, 
                                            :tipo_id =>u.tipo.sigla,
                                            :transportadora_id =>u.transportadora.nome,
                                            :status_id =>u.status.sigla,
                                            :created_at => created_at,
                                            :ended_at => ended_at,
											:released_at =>released_at,
                                            :obs_trans =>u.obs_trans,
                                            :etiqueta =>u.etiqueta,
                                            :carro =>u.carro,
                                            :itinerario =>u.itinerario,
                                            :user_id =>u.user.login,	
											:updated_at => updated_at,
											:depositos => u.nome_depositos(u.id),
											:entrou_em_box => entrou_em_box,
											:em_box => u.tempo_em_box
											} }  
		return return_data.to_json											
	end
	
    protected

    def load_items
        @destino = Destino.find(:all).collect {|d| [d.sigla, d.id]}
        @transportadora = Transportadora.find(:all).collect {|t| [t.nome, t.id]}
        @status = Status.find(:all).collect {|s| [s.sigla, s.id]}
        @tipo = Tipo.find(:all).collect {|t| [t.sigla, t.id]}
        @deposito = Deposito.find(:all, :order => "id asc").collect {|d| [d.nome, d.id, d.qtbox]}
#        horas = []
        #        (1..59).each { |h| h.to_s.size == 1 ? horas << ["0#{h}", "0#{h}".to_i] : horas << [h,h]}
        #        @horas = horas
    end
end
